<template>
  <div class="uploadContainer">
    <Upload
      :headers="tokenHearder"
      multiple
      type="drag"
      :max-size="maxSize"
      :data="fileList"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
      :before-upload="handleBeforeUpload"
      ref="upload"
      :show-upload-list="false"
    >
      <div style="padding: 20px 0">
        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
        <p>
          Select file or drag file to upload (file size should not exceed 300M)
        </p>
        <p>Click or drag files here to upload</p>
      </div>
    </Upload>
    <div style="padding: 20px; max-height: 200px; overflow-y: auto">
      <ul class="file-list" v-for="(list, index) in uploadList" :key="index">
        <li>
          文件名: <span style="font-size: 15px">{{ list.name }}</span>
          <!-- <Icon
            type="ios-close"
            size="20"
            style="float: right"
            v-if="!list.upload"
            @click="delFileList(index)"
          ></Icon> -->
          <!-- <span v-if="list.upload" style="float: right">完成</span>
          <span v-else style="float: right">失败</span> -->
        </li>
      </ul>
    </div>
    <div style="text-align: center">
      <Button @click="upload" type="primary" v-privilege="'assets-list-query'"
        >Upload</Button
      >
    </div>
  </div>
</template>

<script>
import cookie from "@/lib/cookie.js";
import { fileApi } from "@/api/file.js";
import axios from "axios";
export default {
  name: "upload",
  components: {},
  props: {
    //是否为更新表单
    parentFolderId: {
      type: Number,
      default: 1,
    },
    show: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      filterText: null,
      uploadPath: "",
      maxSize: 300 * 1024,
      tokenHearder: "",
      fileId: 1, //1为文件 0为文件夹
      fileList: [],
      uploadList: [],
    };
  },
  watch: {
    parentFolderId: function (newValue, oldValue) {
      this.fileId = newValue;
      this.uploadPath = fileApi.fileUploadLocalUrl + this.fileId;
      this.uploadList = []
    },
    show: function(newValue) {
      this.uploadList = []
    }
  },
  mounted() {
    //初始化获取一级文件夹
    this.uploadPath = fileApi.fileUploadLocalUrl + this.fileId;
    //初始化获取token
    this.tokenHearder = { "x-access-token": cookie.getToken() };
  },
  created() {
      this.uploadList = []
      },
  methods: {
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleSuccess(res, file) {
      this.$Message.success(res.msg);
      this.$emit("on-form-close");
    },
    handleError(res, file) {
      this.$Message.error(res.msg);
      console.log(res, file, 222222222222222);
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "The file format is incorrect",
        desc:
          "File format of " +
          file.name +
          " is incorrect, please select jpg or png.",
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件大小超出300M",
        desc: "File  " + file.name + " is too large, no more than 300M.",
      });
    },
    handleBeforeUpload(data1, data2) {
      this.uploadList.push(data1);
      return false;
    },
    async upload() {
      console.log(this.uploadList)
      if (this.uploadList.length > 0) {
        let file = Array.from(this.uploadList);
        let newArr = this.group(file,10)
        let len = newArr.length
        console.log(newArr.length)
        for (var i = 0; i < newArr.length; i++) {
            let arr = newArr[i]
            let formData = new FormData();
            for(let j = 0; j < arr.length; j++) {
                formData.append("files", arr[j]);
            }
            this.$Message.success('开始上传')
            let s = await this.uploadOne(formData);
            --len
            console.log(len)
            if(len == 0) {
              this.$Message.success('已全部上传');
              this.$emit("on-form-close");
            }
           console.log(s)
        }
      } else {
        this.$Message.error("请至少上传一个文件");
      }
    },
    uploadOne(formData) {
        return new Promise((resolve,reject) => {
            axios.post(fileApi.localMultiUpload + this.fileId, formData, {
              timeout: 20000,
              headers: {
                "Content-Type": "multipart/form-data",
                "x-access-token": cookie.getToken(),
              },
            }).then(res => {
                if(res.data.success) this.$Message.success('上传成功');
                this.$emit("queryFile");
                resolve(res)
            }).catch(err => {
                this.$Message.success(err.message);
                reject(err)
            })
        })
    },
    group(array, subGroupLength) {
      let index = 0;
      let newArray = [];
      while(index < array.length) {
          newArray.push(array.slice(index, index += subGroupLength));
      }
      return newArray;
  },
    delFileList(index) {
      this.uploadList.splice(index, 1);
    },
    setFileList(index) {
        this.uploadList[index].upload = true
    }
  },
};
</script>
<style lang="less">
// .uploadContainer {
//   height: 350px;
//   .ivu-upload-list {
//     height: 200px;
//     overflow-y: auto;
//   }
// }
</style>